package cn.b.sky.shop.storage.utils;


import cn.b.sky.shop.storage.Progress;
import cn.b.sky.shop.storage.ProgressListener;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 */
public class ProgressAwareInputStream extends FilterInputStream {
    private final ProgressListener listener;
    private volatile boolean cancelled = false;
    private final Progress progress = new Progress();


    public ProgressAwareInputStream(InputStream in, long total, ProgressListener listener) {
        super(in);
        progress.setTotal(total);
        this.listener = listener;
    }

    @Override
    public int read() throws IOException {
        if (cancelled) {
            return -1;
        }
        int ret = super.read();
        if (ret != -1) {
            progress.addCompleted(1);
            if (listener != null) {
                listener.onProgress(progress);
            }
        }
        return ret;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (cancelled) {
            return -1;
        }
        int ret = super.read(b, off, len);
        if (ret != -1) {
            progress.addCompleted(ret);
            if (listener != null) {
                listener.onProgress(progress);
            }
        }
        return ret;
    }

    /**
     * cancel以后，会读取到流结束标识
     *
     * @return
     */
    public boolean cancel() {
        boolean c = this.cancelled;
        this.cancelled = true;
        return !c;
    }

    public void setCompleted(long completed) {
        this.progress.setCompleted(completed);
    }

    public long getCompleted() {
        return this.progress.getCompleted();
    }

}
